package org.itheima.service.impl;

import org.apache.ibatis.annotations.Select;
import org.itheima.mapper.ShouCangMapper;
import org.itheima.mapper.UserSearchHistoryMapper;
import org.itheima.mapper.WarehouseMapper;
import org.itheima.pojo.UserSearchHistory;
import org.itheima.pojo.Warehouse;
import org.itheima.service.RecommendationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class RecommendationServiceImpl implements RecommendationService {

    @Autowired
    private UserSearchHistoryMapper userSearchHistoryMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;


    @Autowired
    private ShouCangMapper shouCangMapper;

    public List<Map> getRecommendedProducts(int userId,String username) {
        // 获取用户最近的搜索记录
        List<Map<String,Object>> historyList = userSearchHistoryMapper.findById(userId);
        System.out.println("historyList是："+historyList);
        List<Map<String,Object>> shouCangList = shouCangMapper.shouCangFindById(username);
        System.out.println("shouCangLisy是:"+shouCangList);
        historyList.addAll(shouCangList);
        if (historyList.isEmpty()) return Collections.emptyList();

        // 解析搜索关键词
        List<String> searchKeywords = historyList.stream()
                .map(map -> (String) map.get("search_term")) // 从 Map 获取 "search_term" 字段
                .filter(Objects::nonNull) // 过滤掉 null 值，避免异常
                .distinct()
                .collect(Collectors.toList());

        List<String> searchKeywords1 = historyList.stream()
                .map(map -> (String) map.get("name")) // 从 Map 获取 "search_term" 字段
                .filter(Objects::nonNull) // 过滤掉 null 值，避免异常
                .distinct()
                .collect(Collectors.toList());

        searchKeywords.addAll(searchKeywords1);

        System.out.println("searchKeywords是:"+searchKeywords);

        // 计算相似度并排序
        Map<Map, Double> similarityMap = new HashMap<>();
        for (String keyword : searchKeywords) {
            List<Map<String, Object>> matchedProducts = warehouseMapper.findByTitle(keyword);
            for (Map<String, Object> product : matchedProducts) {
                double similarity = computeSimilarity(keyword, product.get("name") + " " );
                similarityMap.put( product, similarityMap.getOrDefault(product, 0.0) + similarity);
            }
        }

        System.out.println("similarityMap是："+similarityMap);

        // 按相似度排序并返回前100个
        return similarityMap.entrySet().stream()
                .sorted((a, b) -> Double.compare(b.getValue(), a.getValue()))
                .limit(100)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }

    // 计算关键词的余弦相似度
    public double computeSimilarity(String keyword, String productText) {
        System.out.println(keyword);
        System.out.println(productText);
        Set<String> allWords = new HashSet<>(Arrays.asList(keyword.toLowerCase().split(" ")));
        allWords.addAll(Arrays.asList(productText.toLowerCase().split(" ")));

        Map<String, Integer> keywordVector = new HashMap<>();
        Map<String, Integer> productVector = new HashMap<>();

        for (String word : keyword.split(" ")) {
            keywordVector.put(word, keywordVector.getOrDefault(word, 0) + 1);
        }
        for (String word : productText.split(" ")) {
            productVector.put(word, productVector.getOrDefault(word, 0) + 1);
        }

        double dotProduct = 0, normKeyword = 0, normProduct = 0;
        for (String word : allWords) {
            int x = keywordVector.getOrDefault(word, 0);
            int y = productVector.getOrDefault(word, 0);
            dotProduct += x * y;
            normKeyword += x * x;
            normProduct += y * y;
        }

        return dotProduct / (Math.sqrt(normKeyword) * Math.sqrt(normProduct));

    }
}
